﻿using System;
using System.IO;
using System.Reflection;

namespace ooWii.Security
{
	public class KeyStore
	{
		#region KeyStore

		public static void RootKey( out byte[] rootKeyModulus, out byte[] rootKeyExponent )
		{
			Stream rootStream = openKey( "root-key" );

			try
			{
				rootKeyModulus = new byte[ 0x200 ];
				if( rootStream.Read( rootKeyModulus, 0, rootKeyModulus.Length ) != rootKeyModulus.Length )
				{
					throw new WiiException( "Cannot read root key modulus" );
				}

				rootKeyExponent = new byte[ 0x4 ];
				if( rootStream.Read( rootKeyExponent, 0, rootKeyExponent.Length ) != rootKeyExponent.Length )
				{
					throw new WiiException( "Cannot read root key exponent" );
				}

			}
			finally
			{
				rootStream.Close();
			}
		}

		public static void GetKey( byte keyNumber, out byte[] key )
		{
			string keyName = getKeyName( keyNumber );
			Stream stream = openKey( keyName );

			try
			{
				key = new byte[ 16 ];

				if( stream.Read( key, 0, key.Length ) != key.Length )
				{
					throw new WiiException( string.Format( "Cannot read {0}", keyName ) );
				}
			}
			finally
			{
				stream.Close();
			}
		}

		static string getKeyName( byte keyNumber )
		{
			switch( keyNumber )
			{
			case 0:
				return "common-key";

			case 1:
				return "korean-key";

			default:
				throw new WiiException( "Invalid key number" );
			}

		}

		static Stream openKey( string keyName )
		{
			string keyPath = Path.GetDirectoryName( Assembly.GetExecutingAssembly().Location );
			return File.OpenRead( Path.Combine( keyPath, keyName ) );
		}

		#endregion
	}
}
